document.write("<script type=\"text/javascript\" src=\"resources/JavaScript/utils.js\"></script>");
document.write("<script type=\"text/javascript\" src=\"resources/JavaScript/common.js\"></script>");
document.write("<script type=\"text/javascript\" src=\"resources/JavaScript/reuseCore.js\"></script>");
document.write("<script type=\"text/javascript\" src=\"resources/JavaScript/formulaScreen.js\"></script>");
var imgLinkSource = "resources/images/btnLink.gif";
var imgRemoveSource = "resources/images/btnRemove.png";
var imgUpSource = "resources/images/btnUp.png";
var imgDownSource = "resources/images/btnDown.png";
var imgAddSource = "resources/images/btnAdd.png";
var imgFormulaSource = "resources/images/btnFormula.png";
    	
//------------------- JS Event functions  ---------------------- //

function updateOtherOcurrences_JSEvent(oParameter){ updateOtherOcurrences(arguments[0].srcElement); }
function updateResult_JSEvent(oParameter){ updateResult(arguments[0].srcElement); }
function crtNameChanged_JSEvent(oParameter){ crtNameChanged(arguments[0].srcElement); }
function reuseCriterion_JSEvent(oParameter){ reuseCriterion(arguments[0].srcElement); }
function reuseCase_JSEvent(oParameter){ reuseCase(arguments[0].srcElement); }
function reuseValue_JSEvent(oParameter){ reuseValue(arguments[0].srcElement); }
function addCriterion_JSEvent(oParameter){ addCriterion(arguments[0].srcElement); }
function removeCriterion_JSEvent(oParameter){ removeCriterion(arguments[0].srcElement); }
function addCase_JSEvent(oParameter){ before_addMetCase(arguments[0].srcElement); }
function showValueOrigin_JSEvent(oParameter){ showOrigin('value', arguments[0].srcElement); }
function showCriterionOrigin_JSEvent(oParameter){ showOrigin('criterion', arguments[0].srcElement); }
function showFormula_JSEvent(oParameter){ showFormula(arguments[0].srcElement);}
function moveCriterionUp_JSEvent(oParameter){moveParameter(true, arguments[0].srcElement);}
function moveCriterionDown_JSEvent(oParameter){moveParameter(false, arguments[0].srcElement);}

//------------------------------------------------------------- //

function before_addMethod()
{
	var cases =  [{"name": "", "ID": generateID()}, {"name": "", "ID": generateID()}];
	var reqCases = getXmlHttpRequestObject();
	
	function handleRequest()  
	{  
	    if (reqCases.readyState == 4 && reqCases.status == 200) 
	    {
	     	eval("var response = ("+reqCases.responseText+")");
	     	if(response != "ERROR" && response.length > 0)
	     		cases = response;
	    }
	}
		
	sendRequest(reqCases, "method", "loadRelatedCases", handleRequest);
	
	var mainCrt = {"ID": generateID(), "name": "", "description": "", "cases": cases};
	var mainMet = {"ID": generateID(), "name": "", "parameters": [{"name": "", "ID": generateID()}, {"name": "", "ID": generateID()}, {"name": "", "ID": generateID()}]};
	
	addMethod(mainCrt, mainMet);
}

function addMethod(mainCrt, mainMet)
{
	var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
	
	try
	{
		mainMet.ID = generateID();
		var colCount = mainCrt.cases.length *3 + 1;
		var tab = document.createElement("table");
		tab.setAttribute("id", mainCrt.ID);
		tab.setAttribute("class", "table");
		tab.setAttribute("title", mainCrt.name);
		tab.setAttribute("summary", "methodProperties");
		
		var tabHead = document.createElement("thead");
			
		//Creating first table line...
		var row = tabHead.insertRow(0);
		var rowCell1 = row.insertCell(0);
		rowCell1.setAttribute("class","tableHeader");
		rowCell1.setAttribute("colspan", colCount); 
		rowCell1.setAttribute("id","nameHeader" + mainCrt.ID);
		var mainCrtName = createInputField("name" + mainCrt.ID, "", "text", mainCrt.name, "tableCaption", "onchange", crtNameChanged_JSEvent);
		var btnMainCrtReuse = createImageButton("link" + mainCrt.ID, imgLinkSource, reuseValue_JSEvent, "smallImgButton");
		rowCell1.appendChild(mainCrtName);
		rowCell1.appendChild(btnMainCrtReuse);
		
		//Creating second table line...
		var row2 = tabHead.insertRow(1);
		var row2Cell1 = row2.insertCell(0);
		row2Cell1.setAttribute("colspan", colCount); 
		row2Cell1.setAttribute("id","descriptionHeader" + mainCrt.ID);
		var description = document.createElement("textarea");
		description.setAttribute("id","description" + mainCrt.ID);
		description.setAttribute("class", "criterionDescription");
		description.innerHTML = mainCrt.description;
		row2Cell1.appendChild(description);
		
		//Creating third table line...
		var row3 = tabHead.insertRow(2);
		var row3Cell1 = row3.insertCell(0);
		row3Cell1.setAttribute("class","parameterHeader");
		row3Cell1.innerHTML = "Criteria - Parameter";
		
		for(var i = 0 ; i < mainCrt.cases.length ; i++)
		{
			var mainMetAppIdentifer = createInputField(generateID(), "methodApplications" + mainCrt.ID + mainCrt.cases[i].ID, "hidden");
			row3.appendChild(mainMetAppIdentifer);
			var caseIdentifier = createInputField(mainCrt.cases[i].ID, "caso" + mainCrt.ID, "hidden");
			row3.appendChild(caseIdentifier);
			
			var row3cell2 = row3.insertCell(row3.cells.length);
			var newCaseName = createInputField("name" + caseIdentifier.id, "", "text", mainCrt.cases[i].name); 
			var btnCaseReuse = createImageButton("link" + mainCrt.cases[i].ID, imgLinkSource, reuseCase_JSEvent, "smallImgButton");
			row3cell2.setAttribute("class", "tableHeader");
			row3cell2.appendChild(newCaseName);
			row3cell2.appendChild(btnCaseReuse);
		}
		
		var row3Cell3 = row3.insertCell(row3.cells.length);
		var addCase = createInputField(mainCrt.ID, "", "button", "Add Case", "buttonStyle", "onclick", addCase_JSEvent);
		row3Cell3.appendChild(addCase);
		tab.appendChild(tabHead);
		
		var tabBody = document.createElement("tbody");
		var mainMethodIdentifier = createInputField("method" + mainCrt.ID, "", "hidden", mainMet.ID);
		tabBody.appendChild(mainMethodIdentifier);
		
		//Creating parameters rows...
		for(var i = 0 ; i < 3 ; i++)
		{
			var paramID = generateID();
			var paramIdentifier = createInputField(paramID, "params" + mainMet.ID, "hidden");
			tabBody.appendChild(paramIdentifier);
			var bodyRow = tabBody.insertRow(0);
			bodyRow.setAttribute("id", "param" + paramID);
			var cell1 = document.createElement("td");
			var paramName = createInputField("name" + paramID, "name" + paramID, "text", mainMet.parameters[i].name, "largeTextBox");
			var btnParamReuse = createImageButton("link" + paramID, imgLinkSource, reuseCriterion_JSEvent, "smallImgButton");
			cell1.appendChild(paramName);
			cell1.appendChild(btnParamReuse);
			bodyRow.appendChild(cell1);
			
			for(var j = 0 ; j < mainCrt.cases.length ; j++)
			{
				var metAppIdentifier = createInputField(generateID(), "methodApplications" + paramID + mainCrt.cases[j].ID, "hidden");
				var paramMetIdentifier = createInputField(generateID(), "methods" + paramID, "hidden", mainCrt.cases[j].ID);
				var valueIdentifier = createInputField("value" + paramMetIdentifier.id + mainCrt.cases[j].ID, "", "hidden", generateID());
				tabBody.appendChild(metAppIdentifier);
				tabBody.appendChild(paramMetIdentifier);
				tabBody.appendChild(valueIdentifier);
				
				var cell2 = document.createElement("td");
				var valueResult = createInputField("result" + valueIdentifier.value, "result" + valueIdentifier.value, "text", "", "mediumTextBox");
				var valueUnit = createInputField("unit" + valueIdentifier.value, "unit" + valueIdentifier.value, "text", "", "smallTextBox");
				var btnValueReuse = createImageButton("link" + paramID, imgLinkSource, reuseValue_JSEvent, "smallImgButton");
				cell2.appendChild(valueResult);
				cell2.appendChild(valueUnit);
				cell2.appendChild(btnValueReuse);
				bodyRow.appendChild(cell2);
			}
			
			var cell3 = document.createElement("td");
			var btnUp = createImageButton("img" + paramID, imgUpSource, moveCriterionUp_JSEvent, "smallImgButton");
			var btnDown = createImageButton("img" + paramID, imgDownSource, moveCriterionDown_JSEvent, "smallImgButton");
			var btnRemove = createImageButton("img" + paramID, imgRemoveSource, removeCriterion_JSEvent, "smallImgButton");
			cell3.appendChild(btnUp);
			cell3.appendChild(btnDown);
			cell3.appendChild(btnRemove);
			bodyRow.appendChild(cell3);
		}
		
		var rowAddParameter = tabBody.insertRow(tabBody.rows.length);
		var addParameter = createImageButton(mainCrt.ID, imgAddSource, addCriterion_JSEvent, "smallImgButton");
		addParameter.name = "addParameter";
		rowAddParameter.appendChild(addParameter);
		
		//Creating seventh table row...
		var row7 = tabBody.insertRow(tabBody.rows.length);
		var row7Cell1 = row7.insertCell(0);
		row7Cell1.setAttribute("class","measureHeader");
		row7Cell1.setAttribute("colspan", colCount); 
		row7Cell1.setAttribute("id","derivedMeasures" + mainCrt.ID);
		row7Cell1.innerHTML = "Criteria - Derived";
		
		//Creating eighth table row...
		var row8 = tabBody.insertRow(tabBody.rows.length);
		var row8Cell1 = row8.insertCell(0);
		var rbMethodOutput = createInputField(mainMet.ID, mainMet.ID, "radio", mainCrt.ID);
		rbMethodOutput.setAttribute("checked", "checked");
		var methodOutputName = createInputField("methodOutput" + mainMet.ID, "", "text", "", "largeTextBox");
		row8Cell1.appendChild(rbMethodOutput);
		row8Cell1.appendChild(methodOutputName);
		
		for(var i = 0 ; i < mainCrt.cases.length ; i++)
		{
			var value = {"ID": generateID(), "stringResult": "", "unit":"", "source": ""};
			
			var resultIdentifier = createInputField(mainCrt.cases[i].ID + mainCrt.ID, "", "hidden", value.ID);
			row8.appendChild(resultIdentifier);
			
			var row8Cell2 = row8.insertCell(row8.cells.length);
			var resultLabel = document.createElement("label");
			resultLabel.innerHTML = "NONE";
			resultLabel.setAttribute("class", "resultLabel");
			resultLabel.setAttribute("id", "result" + value.ID);
			resultLabel.setAttribute("title", "Source: " + value.source);
			resultLabel.onClick = showFormula_JSEvent;
			resultLabel.attachEvent("onclick", showFormula_JSEvent);
			var resultUnit = createInputField("unit" + value.ID, "unit" + value.ID, "text", "???", "smallTextBox", "onchange", updateOtherOcurrences_JSEvent);	
			var resultReuse = createImageButton("formula" + value.ID, imgFormulaSource, showFormula_JSEvent, "smallImgButton");
			row8Cell2.appendChild(resultLabel);
			row8Cell2.appendChild(resultUnit);
			row8Cell2.appendChild(resultReuse);
		}
		
		//Creating last table row...
		var lastRow = tabBody.insertRow(tabBody.rows.length);
		var lastRowCell = lastRow.insertCell(0);
		var addDerMeasure = createImageButton(mainCrt.ID, imgAddSource, addCriterion_JSEvent, "smallImgButton");
		addDerMeasure.name = "addDerivedMeasure";
		lastRowCell.appendChild(addDerMeasure);
		
		tab.appendChild(tabBody);
		document.getElementById("frMethod").appendChild(tab);
	}
	catch(ex)
	{
		showErrorMessage("There was a problem while trying to insert a new method to the Business Case and the action couldn't be completed.", "Javascript Error");
		document.getElementById("frMethod").innerHTML = cachedForm;
	}
}

function before_addMetCase(srcElement)
{
	var metID = document.getElementById("method" + srcElement.id).value;
	addMetCase(srcElement, {"name": "", "ID": generateID(), "values": []}, metID);
}

function addMetCase(srcElement, caso, metID)
{
	var table = findParentByTagName(srcElement, "TABLE");
	//IE BUG: We have to use the innerHTML from the form because the IE has a bug that doesn't allow to change the table.innerHTML
	var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
	
	try
	{
		var caseIdentifier = createInputField(caso.ID, "caso" + table.id, "hidden");
		table.appendChild(caseIdentifier);
		
		//Inserting new Cells in row 3
		var row3 = table.rows[2];
		var row3cell1 = row3.insertCell(row3.cells.length-1);
		row3cell1.setAttribute("class", "tableHeader"); 
		var newCaseName = createInputField("name" + caseIdentifier.id, "", "text", caso.name);
		var btnCaseReuse = createImageButton("link" + caso.ID, imgLinkSource, reuseValue_JSEvent, "smallImgButton");
		row3cell1.appendChild(btnCaseReuse);
		row3cell1.appendChild(newCaseName);
		
		var metParameters = document.getElementsByName("params" + metID);
		for(var i = 0 ; i < metParameters.length ; i++)
		{
			var metID = generateID();
			var value = null;
			
			var caseValue = caso.values[metParameters[i].id];
			if(caseValue == null)
				value = {"ID": generateID(), "stringResult": "", "unit": ""};
			else
			{
				metID = caseValue.methodID;
				value = caseValue.value;
			}
			
			var paramRow = table.rows[i+3];
			var newParamRowCell = paramRow.insertCell(paramRow.cells.length-1);
			
			var metIdentifier = createInputField(metID, "", "hidden", "methods" + metParameters[i].id);
			table.appendChild(metIdentifier);
			
			var valueIdentifier = createInputField("value" + metID,"", "hidden", value.ID);
			newParamRowCell.appendChild(valueIdentifier);
			
			var vResult = createInputField("result" + value.ID, "result" + value.ID, "text", value.stringResult, "mediumTextBox", "onchange", updateResult_JSEvent);
			newParamRowCell.appendChild(vResult);
			
			var vUnit = createInputField("unit" + value.ID, "unit" + value.ID, "text", value.unit, "smallTextBox", "onchange", updateResult_JSEvent);
			newParamRowCell.appendChild(vUnit);
			
			var btnValueReuse = createImageButton("link" + caso.ID, imgLinkSource, reuseValue_JSEvent, "smallImgButton");
			newParamRowCell.appendChild(btnValueReuse);
		}
		
		document.getElementById("nameHeader" + table.id).setAttribute("colspan", row3.cells.length);;
		document.getElementById("descriptionHeader" + table.id).setAttribute("colspan", row3.cells.length);;
		document.getElementById("derivedMeasures" + table.id).setAttribute("colspan", row3.cells.length);;
	}
	catch(ex)
	{
		showErrorMessage("There was a problem while trying to insert a new parameter (criterion) to the method and the action couldn't be completed.", "Javascript Error");
		document.getElementById("frMethod").innerHTML = cachedForm;
	}
}

function addCriterion(srcElement)
{
	var addFunction = srcElement.name;
	var metID = document.getElementById("method" + srcElement.id).value;
	if(addFunction == "addParameter")
		addParameter(srcElement, {"name": "", "ID": generateID(), "values": []}, metID);
	else
		addDerivedMeasure(srcElement, metID);
}

function addDerivedMeasure(srcElement, metID)
{
	var table = findParentByTagName(srcElement, "TABLE");
	
	//IE BUG: We have to use the innerHTML from the form because the IE has a bug that doesn't allow to change the table.innerHTML
	var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
	
	try
	{
		var currentRow = findParentByTagName(srcElement, "TR");
		var newRow = table.insertRow(table.rows.length-3);
		
		var derMeasureID = generateID();
		var newRowCell1 = newRow.insertCell(0);
		var rbDerMeasure = createInputField(metID, metID, "radio", derMeasureID);
		var measureName = createInputField("","measures" + metID, "text", "", "largeTextBox");
		newRowCell1.appendChild(rbDerMeasure);
		newRowCell1.appendChild(measureName);
		
		var cases = document.getElementsByName("caso" + table.id); 
		for(var i = 0 ; i < cases.length ; i++)
		{
			var valueID = generateID();
			var derMeasureValueIdentifier = createInputField(cases[i].ID + derMeasureID, "", "hidden", valueID);
			newRow.appendChild(derMeasureValueIdentifier);
			
			var column2 = newRow.insertCell(1);
			var vResult = document.createElement("label");
			vResult.id = "result + valueID";
			vResult["onclick"] = showFormula_JSEvent;
			vResult.innerHTML = "NONE";
			vResult.setAttribute("class","resultLabel");
			var vUnit = createInputField("unit" + valueID, "unit" + valueID, "text", "???", "smallTextBox", "onchange", updateOtherOcurrences_JSEvent);
			var btnReuse = createImageButton("formula" + valueID, imgFormulaSource, showFormula_JSEvent, "smallImgButton");
			column2.appendChild(vResult);
			column2.appendChild(vUnit);
			column2.appendChild(btnReuse);
		}
		
		currentRow.parentNode.insertBefore(newRow, currentRow);
	}
	catch(ex)
	{
		showErrorMessage("There was a problem while trying to insert a new parameter (criterion) to the method and the action couldn't be completed.", "Javascript Error");
		document.getElementById("frMethod").innerHTML = cachedForm;
	}
}

function addParameter(srcElement, criterion, metID)
{
	var table = findParentByTagName(srcElement, "TABLE");
	
	//IE BUG: We have to use the innerHTML from the form because the IE has a bug that doesn't allow to change the table.innerHTML
	var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
	
	try
	{
		var currentRow = findParentByTagName(srcElement, "TR");
		var newRow = table.insertRow(table.rows.length-3);
		
		var paramIdentifier = createInputField(criterion.ID, "params" + metID, "hidden");
		table.appendChild(paramIdentifier);
		
		newRow.setAttribute("id", "param" + paramIdentifier.id);
		
		var column1 = newRow.insertCell(0);
		var tbxCrtName = createInputField("name" + paramIdentifier.id, "name" + paramIdentifier.id, "text", criterion.name, "largeTextBox");
		var btnCrtReuse = createImageButton("link" + paramIdentifier.id, imgLinkSource, reuseCriterion_JSEvent, "smallImgButton");
		column1.appendChild(tbxCrtName);
		column1.appendChild(btnCrtReuse);
		
		var cases = document.getElementsByName("caso" + table.id); 
		for(var i = 0 ; i < cases.length ; i++)
		{
			var crtValue = {"value": {"ID": generateID(), "stringResult": "", "unit": "", "source": ""}, "methodID": generateID(), "metAppID": generateID()};
			
			var metAppIdentifier = createInputField(crtValue.metAppID, "methodApplications" + paramIdentifier.id + cases[i].id, "hidden");
			newRow.appendChild(metAppIdentifier);
			
			var metIdentifier = createInputField(crtValue.metID, "methods" + paramIdentifier.id , "hidden", cases[i].id);
			newRow.appendChild(metIdentifier);
			
			var valueIdentifier = createInputField("value" + crtValue.metID + cases[i].id, "", "hidden", crtValue.value.ID);
			newRow.appendChild(valueIdentifier);
			
			var column2 = newRow.insertCell(1);
			var vResult = createInputField("result" + crtValue.value.ID, "result" + crtValue.value.ID, "text", crtValue.value.stringResult, "mediumTextBox", "onchange", updateResult_JSEvent);
			var vUnit = createInputField("unit" + crtValue.value.ID, "unit" + crtValue.value.ID, "text", crtValue.value.unit, "smallTextBox", "onchange", updateOtherOcurrences_JSEvent);
			var btnReuse = createImageButton("link" + paramIdentifier.id, imgLinkSource, reuseCriterion_JSEvent, "smallImgButton");
			column2.appendChild(vResult);
			column2.appendChild(vUnit);
			column2.appendChild(btnReuse);
		}
		
		var column3 = document.createElement("td");
		var btnUp = createImageButton("img" + metID, imgUpSource, moveCriterionUp_JSEvent, "smallImgButton");
		var btnDown = createImageButton("img" + metID, imgDownSource, moveCriterionDown_JSEvent, "smallImgButton");
		var btnRemove = createImageButton("img" + metID, imgRemoveSource, removeCriterion_JSEvent, "smallImgButton");
		column3.appendChild(btnUp);
		column3.appendChild(btnDown);
		column3.appendChild(btnRemove);
		newRow.appendChild(column3);
		
		currentRow.parentNode.insertBefore(newRow, currentRow);
	}
	catch(ex)
	{
		showErrorMessage("There was a problem while trying to insert a new parameter (criterion) to the method and the action couldn't be completed.", "Javascript Error");
		document.getElementById("frMethod").innerHTML = cachedForm;
	}
}

function encapsulateAllJSONData()
{
	var jsonData = [];
	var methods = [];
		
	var allTables = document.getElementsByTagName("table");
		
	for (var i=0; i < allTables.length; i++) //Necessary loop to take only the tables that represent methods and not the SAPUI5 tables.
		if(allTables[i].summary == "methodProperties")
			methods.push(allTables[i]); //Add only the methods tables
		
	for(var i=0; i < methods.length; i++)
	{
		var jsonMethodApplications = encapsulateJSONData(methods[i]);
		jsonData.push(jsonMethodApplications);
	}
		
	return jsonData;
}

function encapsulateJSONData(table)
{
	var methodApplications = [];
	var jsonMethodApplications = {"mainMethod": {}, "cases": [], "methodApplications": methodApplications, "derMeasure": null};
	
	var crtID = table.id;
	var mainCrtName = document.getElementById("name" + crtID).value;
	var mainDescription = document.getElementById("description" + crtID).value;
	jsonCriterion = {"ID": crtID, "name": mainCrtName, "description": mainDescription}; 
	var mainMetID = getChildElementByProperty(table, "id", "method" + crtID).value;
	var jsonMainMethod = {"ID": mainMetID, "name": getChildElementByProperty(table, "id", "methodOutput" + mainMetID).value, "parameters": []}; 
	var jsonCases = [];
	
	var radioButtons = getChildElementsByProperty(table, "name", mainMetID);
	for(var j = 0 ; j < radioButtons.length ; j++)
	{
		var currentMeasure = radioButtons[j];
		if(currentMeasure.checked && currentMeasure.defaultValue != crtID)
			jsonMethodApplications.derMeasure = {"ID": currentMeasure.value, "name": getChildElementByProperty(table, "name", "measures" + jsonMainMethod.ID).value}; 
	}
	
	var criterionCases = getChildElementsByProperty(table, "name", "caso" + crtID);
	for(var j = 0 ; j < criterionCases.length ; j++)
	{
		var caseID = criterionCases[j].id;
		var caseName = document.getElementById("name" + caseID).value;
		var jsonCase = {"ID": caseID, "name": caseName}; 
		jsonCases.push(jsonCase);
		
		var valID = getChildElementByProperty(table, "id", caseID + crtID).value; 
		var valResult = getChildElementByProperty(table, "id", "result" + valID).innerHTML; 
		var valUnit = getChildElementByProperty(table, "id", "unit" + valID).value; 
		var jsonValue = {"ID": valID, "stringResult": valResult, "unit": valUnit};
	
		var jsonMethodApplication = {"criterion": {}, "method": {}, "caso": {}, "value": {}, "ID":""};
		
		jsonMethodApplication.criterion = jsonCriterion;
		jsonMethodApplication.method = jsonMainMethod;
		jsonMethodApplication["caso"] = jsonCase;
		jsonMethodApplication.value = jsonValue;
		jsonMethodApplication.ID = getChildElementByProperty(table, "name", "methodApplications" + jsonCriterion.ID + caseID).id;  
		
		methodApplications.push(jsonMethodApplication);
	}
	
	jsonMethodApplications.cases = jsonCases;
	
	var metParameters = getChildElementsByProperty(table, "name", "params" + jsonMainMethod.ID);
	for(var k = 0 ; k < metParameters.length ; k++)
	{
		var paramID = metParameters[k].id;
		var paramName = document.getElementById("name" + paramID).value;
		var jsonParam = {"ID": paramID, "name": paramName};
		
		var methods = getChildElementsByProperty(table, "name", "methods" + paramID); 
		for(var l = 0 ; l < methods.length ; l++)
		{
			var metID = methods[l].id;
			var caseID = methods[l].value;
			
			var valueID = getChildElementByProperty(table, "id", "value" + metID + caseID).value; 
			vResult = getChildElementByProperty(table, "id", "result" + valueID).value; 
			if(vResult == null)
				vResult = getChildElementByProperty(table, "id", "result" + valueID).innerHTML; 
			vUnit = getChildElementByProperty(table, "id", "unit" + valueID).value;
			
			var jsonValue = {"ID": valueID, "stringResult": vResult, "unit": vUnit};
			var jsonMethod = {"ID": metID, "value": jsonValue};
			
			var jsonMethodApplication = {"criterion": {}, "method": {}, "caso": {}, "value": {}, "ID": "", "parentMetID": ""};
			
			jsonMethodApplication.criterion = jsonParam;
			jsonMethodApplication.method = jsonMethod;
			jsonMethodApplication["caso"] = jsonCases.searchElement("ID", caseID);
			jsonMethodApplication.value = jsonValue;
			jsonMethodApplication.parentMetID = mainMetID;
			jsonMethodApplication.ID = getChildElementByProperty(table, "name", "methodApplications" + jsonParam.ID + caseID).id;
			
			methodApplications.push(jsonMethodApplication);
		}
		
		jsonMainMethod.parameters.push(jsonParam);
		jsonMethodApplications.mainMethod = jsonMainMethod;
	}
	
	return jsonMethodApplications;
}

function verifyPendingChanges()
{
	return false;
}

function validateForm()
{
	function prepareParameter(jsonData)
	{
		var param = "&methodApplications=" + transformJSON(jsonData.methodApplications);
		param += "&cases=" + transformJSON(jsonData.cases);
		param += "&mainMethod=" + transformJSON(jsonData.mainMethod);
		
		return param;
	}
	
	var isValid = false;
	var validateReq = getXmlHttpRequestObject();
	var jsonData = encapsulateAllJSONData();
	var i = 0;
	
	function handleError()
    {
    	if (validateReq.readyState == 4 && validateReq.status == 200) 
    	{
    		eval("var response = ("+validateReq.responseText+")");
    		showSpecifcErrorMessage(response);
    	}
    }
	
	function handleRequest()  
	{  
		if (validateReq.readyState == 4 && validateReq.status == 200) 
	    {
	     	eval("var response = ("+validateReq.responseText+")");
	     	
	     	if(response == "")
	     		isValid = true;
	     	else //Treat the possible errors types and show an adequate message...
	     	{
	     		i = jsonData.length;
	     		if(!showSpecifcErrorMessage(response))
		     		showValidationError(response);
	     	}
	    }
	}
	
	for(i = 0 ; i < jsonData.length ; i++)
 		sendRequest(validateReq, "method", "validateChanges", handleRequest, prepareParameter(jsonData[i]));
	
	if(isValid)
	{
		validateReq = getXmlHttpRequestObject();
		sendRequest(validateReq, "method", "saveMethodData", handleError, "&saveData=" + transformJSON(jsonData));
	}
	
	return isValid;
}

function updateOtherOcurrences(sourceElement)
{
	//Update input fields...
	var elements = document.getElementsByName(sourceElement.name);
	for(var i = 0 ; i < elements.length ; i++)
		elements[i].value = sourceElement.value;
	
	//Update hyperlinks...
	var hyperLinks = document.getElementsByTagName("A");
	for(var i = 0 ; i < hyperLinks.length ; i++)
		if(hyperLinks[i].id == sourceElement.id)
			hyperLinks[i].innerHTML = sourceElement.value;
}

function updateResult(oParameter)
{
	updateOtherOcurrences(oParameter);
	var updateReq = getXmlHttpRequestObject();
	
	function handleRequest()  
	{  
		if (updateReq.readyState == 4 && updateReq.status == 200 && updateReq.responseText != "") 
	    {
	     	eval("var response = ("+updateReq.responseText+")");
	     	
	     	if(typeof response != "string")
	     		refreshResultFields(response);
	     	else //Treat the possible errors types and show an adequate message...
	     	{
	     		i = jsonData.length;
	     		showSpecifcErrorMessage(response);
	     	}
	    }
	}
	
	var param = "&valID=" + transformJSON(oParameter.name.replace("result",""));  
	param += "&stringResult=" + encodeURIComponent(oParameter.value);
	sendRequest(updateReq, "method", "updateResult", handleRequest, param);
}

function removeCriterion(srcElement)
{
	try
	{
		function callback(oAction)
		{
			if(oAction == sap.ui.commons.MessageBox.Action.YES)
			{
				var reqRemove = getXmlHttpRequestObject();
				var table = findParentByTagName(srcElement, "TABLE");
				var mainCrtID = table.id;
				var crtID = srcElement.id.replace("img","");
				var calMetID = getChildElementByProperty(table, "id", "method" + mainCrtID).value;
				var methodApplications = [];
				
				function handleRequest()  
				{  
					if (reqRemove.readyState == 4 && reqRemove.status == 200) 
				    {
						eval("var response = (" + reqRemove.responseText + ")");
						if(response == "")
						{
							var currentRow = findParentByTagName(srcElement, "TR");
							currentRow.parentNode.removeChild(currentRow);
							
							var paramIdentifier = getChildElementByProperty(table, "id", crtID);
							paramIdentifier.parentNode.removeChild(paramIdentifier);
						}
						else
							showSpecifcErrorMessage(response);
				    }
				}
				
				var criterionCases = document.getElementsByName("caso" + mainCrtID);
				var crtMethods = document.getElementsByName("methods" + crtID);
				for(var j = 0 ; j < criterionCases.length ; j++)
				{
					var casID = criterionCases[j].id;
					var metAppID = getChildElementByProperty(table, "name", "methodApplications" + crtID + casID).id;
					var metID = crtMethods[j].id;
					var valID = document.getElementById("value" + metID + casID).value;
					var jsonMethodApplication = {"criterion": {"ID": crtID}, "method": {"ID": metID}, "caso": {"ID": casID}, "value": {"ID": valID}, "ID": metAppID};
					methodApplications.push(jsonMethodApplication);
				}
				
				var param = "&crtID=" + transformJSON(crtID);  
				param += "&calMetID=" + transformJSON(calMetID);
				param += "&metApps=" + transformJSON(methodApplications);
				
				sendRequest(reqRemove, "method", "removeParameter", handleRequest, param);
			}
		}
		
		sap.ui.commons.MessageBox.show("Are you sure you want to remove this parameter and all of its related data?", sap.ui.commons.MessageBox.Icon.QUESTION, "Remove Confirmation", [sap.ui.commons.MessageBox.Action.YES, sap.ui.commons.MessageBox.Action.NO], callback);
	}
	catch(ex)
	{ 
		showErrorMessage("There was a problem while trying to remove the parameter from the method and the action couldn't be completed.", "Javascript Error"); 
	}
}

function moveCriterionUp(srcElement)
{
	moveParameter(true, srcElement);
}

function moveCriterionDown(srcElement)
{
	moveParameter(false, srcElement);
}

function moveParameter(moveUp, srcElement)
{
	var currentRow = findParentByTagName(srcElement, "TR");
	var table = findParentByTagName(currentRow, "TABLE");
	var currentIndex = currentRow.rowIndex; 
	if(moveUp)
	{
		var otherRow = table.rows[currentIndex - 1];
		if(otherRow.id.indexOf("param") != -1)
			otherRow.parentNode.insertBefore(currentRow,otherRow);
	}
	else
	{
		var otherRow = table.rows[currentIndex + 1]; 
		if(otherRow.id.indexOf("param") != -1)
			currentRow.parentNode.insertBefore(otherRow,currentRow);
	}
}

function showOrigin(cmpType, srcElement)
{
	var componentReq = getXmlHttpRequestObject();
	
	function handleRequest()  
	{  
		if (componentReq.readyState == 4 && componentReq.status == 200) 
	    {
	     	eval("var response = ("+componentReq.responseText+")");
	     	
	     	if(typeof response != "string")
	     	{
	     		var cmpName = (cmpType == "value") ? response.value.stringResult : response.criterion.name;
	     		var message = "The cmpType 'crtName' is reused from the method 'metName' in Business Case 'XXX'.";
	     		message = message.replace("cmpType", cmpType);
	     		message = message.replace("crtName", cmpName);
	     		message = message.replace("metName", response.method.name);
	     		
	     		showErrorMessage(message);
	     	}
	     	else
	     		showSpecifcErrorMessage(response);
	    }
	}
	var cmpID = srcElement.id.replace("link","");
	var param = "&cmpID=" + encodeURIComponent(cmpID);
	param += "&cmpType=" + encodeURIComponent(cmpType);
	sendRequest(componentReq, "method", "getComponentByID", handleRequest, param);
}